package com.vimi8.ebb.auth.api;

import com.vimi8.ebb.auth.configuration.HttpResponseEntity;
import com.vimi8.ebb.auth.configuration.OAuth2AuthenticationImpl;
import com.vimi8.ebb.auth.dto.AuthUserDto;
import com.vimi8.ebb.auth.dto.OrgMemberTotalDTO;
import com.vimi8.ebb.auth.dto.OrgTotalDTO;
import com.vimi8.ebb.auth.dto.RegUserDto;
import com.vimi8.ebb.auth.manage.OrgManageImpl;
import com.vimi8.ebb.auth.model.*;
import com.vimi8.ebb.auth.model.Error;
import com.vimi8.ebb.auth.service.DBClientDetailsService;
import com.vimi8.ebb.auth.service.GeoCodingsService;
import com.vimi8.ebb.auth.service.OrganizationService;
import com.vimi8.ebb.auth.service.UserAuthorityService;
import com.vimi8.ebb.auth.utils.CommonUtil;
import com.vimi8.ebb.auth.utils.SubStringUtil;
import com.vimi8.ebb.auth.service.RelationService;
import io.swagger.annotations.ApiParam;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.oauth2.client.http.OAuth2ErrorHandler;
import org.springframework.security.oauth2.client.resource.BaseOAuth2ProtectedResourceDetails;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringCodegen", date = "2016-10-11T13:20:24.333Z")

@Controller
public class OrgApiController implements OrgApi {
    protected Logger logger = LoggerFactory.getLogger(this.getClass());
    private String host="127.0.0.1";
    @Value("${server.contextPath}")
    private String contextPath;
    @Value("${server.port}")
    private String port;

    @Autowired
    private OrganizationService organizationService;
    @Autowired
    private GeoCodingsService geoCodingsService;
    @Autowired
    private DBClientDetailsService dbClientDetailsService;
    @Autowired
    private UserAuthorityService userAuthorityService;
    @Autowired
    private OrgManageImpl orgManage;
@Autowired
private RelationService relationService;
//    public static final String COOL_RESOURCE="";
//    public static final String COOL_SCOPES="";

    @Value("${auth-server.auto-resource}")
    private String autoRecource;
    @Value("${auth-server.auto-scopes}")
    private String autoScopes;


//    public HttpResponseEntity<String> orgDeptEmpDelete(@ApiParam(value = "员工id", required = true) @RequestParam(value = "openId", required = true) String openId) {
//        // do some magic!
//        //删掉员工表和oauth_client_user数据即可
//        int count = 0;
//        String clientId = OAuth2AuthenticationImpl.clientId();
//        try {
//            count += organizationService.deleteOrganizationEmpByClientIdAnd(clientId, openId);
//            count += userAuthorityService.deleteAuthorityByClientAndOpentId(clientId, openId);
//        } catch (Exception e) {
//            Error error = new Error().error("delete organizationEmp error").errorDescription("delete organizationEmp exception " + e.getMessage());
//            return new HttpResponseEntity<String>(error, HttpStatus.INTERNAL_SERVER_ERROR);
//        }
//
//        return new HttpResponseEntity<String>(count + "", HttpStatus.OK);
//    }

    /**
     * 删除集体经济组织和服务站点
     *
     * @param clientId
     * @return
     */
    @Override
    public HttpResponseEntity<String> orgUserDelete(@ApiParam(value = "员工id", required = true) @RequestParam(value = "clientId", required = true) String clientId) {

        int count = 0;


        try {
            count += organizationService.deleteOrganization(clientId);//删除组织
            count += userAuthorityService.deleteAuthUser(clientId);//删除user
        } catch (Exception e) {
            Error error = new Error().error("delete organization error").errorDescription("delete auth_user exception " + e.getMessage());
            return new HttpResponseEntity<String>(error, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new HttpResponseEntity<String>(count + "", HttpStatus.OK);
    }



    public HttpResponseEntity<OrganizationDept> orgDeptGet(@ApiParam(value = "部门级别（0：顶级部门(股东)，1：管理部门）", required = true) @RequestParam(value = "deptLevel", required = true) String deptLevel) {
        // do some magic!
        String clientId = OAuth2AuthenticationImpl.clientId();
        OrganizationDept organizationDept = null;
        try {
            organizationDept = organizationService.getOrganizationDept(clientId, deptLevel);
        } catch (Exception e) {
            Error error = new Error().error("query organizationDept error").errorDescription("query organizationDept exception " + e.getMessage());
            return new HttpResponseEntity<OrganizationDept>(error, HttpStatus.INTERNAL_SERVER_ERROR);
        }

        return new HttpResponseEntity<OrganizationDept>(organizationDept, HttpStatus.OK);
    }

    public HttpResponseEntity<String> orgDeptPost(@ApiParam(value = "用户组信息", required = true) @RequestBody OrganizationDept organizationDept) {
        // do some magic!
        int count = 0;
        try {
            count = organizationService.insertOrganizationDept(organizationDept);
        } catch (Exception e) {
            Error error = new Error().error("create organizationDept error").errorDescription("create organizationDept exception " + e.getMessage());
            return new HttpResponseEntity<String>(error, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new HttpResponseEntity<String>(count + "", HttpStatus.OK);
    }

    public HttpResponseEntity<String> orgDeptPut(@ApiParam(value = "需要更新的个人信息", required = true) @RequestBody OrganizationDept organizationDept) {
        // do some magic!
        int count = 0;
        try {
            count = organizationService.updateOrganizationDept(organizationDept);
        } catch (Exception e) {
            Error error = new Error().error("update organizationDept error").errorDescription("update organizationDept exception:" + e.getMessage());
            return new HttpResponseEntity<String>(error, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new HttpResponseEntity<String>(count + "", HttpStatus.OK);
    }

    public HttpResponseEntity<String> orgEmpPost(
            @ApiParam(value = "userId", required = true) @RequestParam(value = "userId", required = true) String userId
            , @ApiParam(value = "部门id（不传的时候默认是0）") @RequestParam(value = "deptId", required = false) String deptId
            , @ApiParam(value = "工种（org_manager:管理员,  org_shareholder：只是股东，不是员工， org_shareholder_emp：既是股东又是员工，org_senior_manager:高级管理员，org_shareholder_manager： 既是管理员又是股东，org_shareholder_senior_manager：既是股东又是高级管理员, org_emp:组织里面的员工）", required = true) @RequestParam(value = "job", required = true) String job
            , @ApiParam(value = "权限范围(普通员工:user，管理员:admin，高级管理员：senior-admin，股东:shareholder，既是管理员又是股东:shareholder|admin,既是股东又是高级管理员：shareholder|senior-admin)", required = true) @RequestParam(value = "scopes", required = true) String scopes

    ) {
        // do some magic!
        //授权给用户
        logger.info("requestUrl=/auth/org/emp/");
        String clientId = OAuth2AuthenticationImpl.clientId();
        logger.info("clientId=" + clientId + ",userId=" + userId);
        int count = 0;
        long startTime = System.currentTimeMillis();
        String openId=null;
        try {
          //  userId=userAuthorityService.getUserIdByOpenId(openId);
            openId=userAuthorityService.getOpenIdIdByUserId(userId);
            ClientUser clientUser = userAuthorityService.getClientUserByOpenid(clientId, openId);
            if (userAuthorityService.getOpenIdAndScopesCount(clientId, openId, scopes,job) > 0) {
                Error error = new Error().error("apply clientResource error").errorDescription("clientId:" + clientId + "已经授权给openId: " + openId);
                return new HttpResponseEntity<String>(error, HttpStatus.INTERNAL_SERVER_ERROR);
            } else if (userAuthorityService.getOpenIdCount(clientId, openId) > 0 && clientUser != null && (!"org_emp".equals(job) || !"org_shareholder".equals(job))) {
                //如果openid对应的权限值不包括传进来的scopes,则把新的scopes追加进去
                LinkedHashSet<String> scopeSet = new LinkedHashSet();
                if (!StringUtils.isEmpty(clientUser.getScopes())) {
                    scopeSet.addAll(Arrays.asList(clientUser.getScopes().split("\\|")));
                }
                scopeSet.addAll(Arrays.asList(scopes.split("\\|")));
                String scopesUpdate = String.join("|", scopeSet);
                count += userAuthorityService.updateScopes(clientId, openId, scopes);
                count += organizationService.updateJob(clientId, openId, job, userId);
                return new HttpResponseEntity<String>(count + "", HttpStatus.OK);
            }

            long clientUserStartTime = System.currentTimeMillis();
            logger.info("query clientUser subTime====" + (clientUserStartTime - startTime) + "");
            logger.info("clientUser=" + clientUser);

            //授权给用户
            //查询当前的客服端的权限，追加到客户端下的openId上

            DBClientDetails clientDetails = dbClientDetailsService.getClientDetailsByClientId(clientId);
            logger.info("clientDetails====" + clientDetails);
            long clientDetailStartTime = System.currentTimeMillis();
            logger.info("query clientDetails subTime====" + (clientDetailStartTime - clientUserStartTime) + "");
            //如果deptId已经存在 用已经存在的部门organizationDept
            OrganizationDept organizationDept = null;
            if (!StringUtils.isEmpty(deptId)) {
                organizationDept = organizationService.getParentOrganizationDeptByDeptId(clientId, deptId);
            }
            logger.info("organizationDept====" + organizationDept);
            if (organizationDept == null) {
                //查询顶级组织部门信息
                organizationDept = organizationService.getParentOrganizationDept(clientId);
                logger.info("organizationDept====" + organizationDept);
                long deptStartTime = System.currentTimeMillis();
                logger.info("query organizationDept subTime====" + (deptStartTime - clientDetailStartTime) + "");
                if (null == organizationDept) {
                    //  没有顶级部门，需要插入顶级部门
                    Organization organization = organizationService.getOrganizationByClient(clientId);
                    organizationDept = new OrganizationDept();
                    organizationDept.setClientId(organization.getClientId());
                    organizationDept.setDeptId(0 + "");
                    organizationDept.setDeptParentId(-1 + "");
                    organizationDept.setDeptName(organization.getOrgClass());
                    organizationDept.setDeptPlace(organization.getAddressCode());
                    organizationDept.setDeptPlaceDetail(organization.getAddressDetail());

                    count += organizationService.insertOrganizationDept(organizationDept);
                }
            }


            logger.info("organizationDept=" + organizationDept);
            //给用户配置自动资源
            String resources = "default_resources";
            LinkedHashSet<String> resourceSet = new LinkedHashSet();
            //参考原客服端的资源
            if (!StringUtils.isEmpty(clientDetails.getAutoResources())) {
                resourceSet.addAll(Arrays.asList(clientDetails.getAutoResources().split("\\|")));
            }
            //访问资源、权限参考部门表
            if (!StringUtils.isEmpty(organizationDept.getDeptScopes())) {
                resourceSet.addAll(Arrays.asList(organizationDept.getDeptResources().split("\\|")));
                resources = String.join("|", resourceSet);
            }
            String scopesAll = "default_scopes";
            //给用户配置自动权限
            //参考客服端的scope
            LinkedHashSet<String> scopeSet = new LinkedHashSet();
            if (!StringUtils.isEmpty(clientDetails.getAutoScopes())) {
                scopeSet.addAll(Arrays.asList(clientDetails.getAutoScopes().split("\\|")));
            }
            if (!StringUtils.isEmpty(organizationDept.getDeptScopes())) {
                scopeSet.addAll(Arrays.asList(organizationDept.getDeptScopes().split("\\|")));
            }

            if (!StringUtils.isEmpty(scopes)) {
                scopeSet.addAll(Arrays.asList(scopes.split("\\|")));

            }
            scopesAll = String.join("|", scopeSet);
            logger.info("scopesAll==" + scopesAll);
            //用户插入组织(client域)
            //数据库，需保证resources,scopes  NOT NULL（已加约束），所以此处resources,scopes不能为null
            count += userAuthorityService.insertOpenid(clientId, userId, openId, resources, scopesAll);

            long openIdStartTime = System.currentTimeMillis();
            //logger.info("insert openId subTime===="+(openIdStartTime-deptStartTime)+"");
            //插入组织员工信息
            OrganizationEmp organizationEmp = new OrganizationEmp();
            organizationEmp.setClientId(organizationDept.getClientId());
            organizationEmp.setDeptId(organizationDept.getDeptId());
            organizationEmp.setUserId(userId);
            organizationEmp.setJob(job);
            count += organizationService.insertOrganizationEmp(organizationEmp);
            long empStartTime = System.currentTimeMillis();
            logger.info(" insertOrganizationEmp subTime====" + (empStartTime - openIdStartTime) + "");
            //修改默认组织id
            if(!"org_shareholder".equals(job)){
                userAuthorityService.updatDefaultClientId(clientId, openId);
            }
          
            long updatDefaultClientIdStartTime = System.currentTimeMillis();
            logger.info(" updatDefaultClientIdStartTime subTime====" + (updatDefaultClientIdStartTime - empStartTime) + "");
            //授权之后删掉该申请记录
            //organizationService.deleteUserApplyClientResource(userApplyClientResource.getUserId(),userApplyClientResource.getClientId());
        } catch (Exception e) {
            Error error = new Error().error("apply clientResource error").errorDescription("apply clientResource exception " + e.getMessage());
            return new HttpResponseEntity<String>(error, HttpStatus.INTERNAL_SERVER_ERROR);
        }

        return new HttpResponseEntity<String>(count + "", HttpStatus.OK);
    }

    public HttpResponseEntity<Organization> orgGet() {
        // do some magic!
        String clientId = OAuth2AuthenticationImpl.clientId();
        Organization organization = null;
        try {
            organization = organizationService.getOrganization(clientId);
        } catch (Exception e) {
            Error error = new Error().error("query organization error").errorDescription("query organization exception " + e.getMessage());
            return new HttpResponseEntity<Organization>(error, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new HttpResponseEntity<Organization>(organization, HttpStatus.OK);
    }

    public HttpResponseEntity<String> orgPost(@ApiParam(value = "用户组信息", required = true) @RequestBody Organization organization) {

        HttpResponseEntity<String> responseEntity = new HttpResponseEntity<String>(HttpStatus.OK);
        Error error = null;
        if (organization == null) {
            error = new Error().error("organization").errorDescription("organization is null");
            responseEntity = new HttpResponseEntity<String>(error, HttpStatus.BAD_REQUEST);
            return responseEntity;
        }
        //组织类型必须传
        if (organization != null && StringUtils.isEmpty(organization.getOrgClass())) {
            error = new Error().error("org_class").errorDescription("org_type is require");
            responseEntity = new HttpResponseEntity<String>(error, HttpStatus.BAD_REQUEST);
            return responseEntity;
        }
        organization.setClientId(UUID.randomUUID().toString());
        try {

            DBClientDetails dbClientDetails = new DBClientDetails();
            dbClientDetails.setClientSecret(UUID.randomUUID().toString());
            //模板信息
            OrganizationClass organizationClass = organizationService.getOrganizationClassByOrgClass(organization.getOrgClass());

            List<String> grantTypes = new ArrayList<>();
            if (!StringUtils.isEmpty(organizationClass.getGrantTypes())) {
                grantTypes = Arrays.asList(organization.getGrantTypes().split("\\|"));
            }
            //组织分类必须传
            dbClientDetails.setAuthorizedGrantTypes(grantTypes);
            dbClientDetails.setGrantTypes(organizationClass.getGrantTypes());
            dbClientDetails.setClientId(organization.getClientId());
            dbClientDetails.setAllowUsersToJoin(organizationClass.getAllowUsersToJoin());
            dbClientDetails.setAutoResources(organizationClass.getAutoApproveResources());
            dbClientDetails.setAutoScopes(organizationClass.getAutoApproveScopes());
            dbClientDetails.setManuResources(organizationClass.getManuApproveResources());
            dbClientDetails.setManuScopes(organizationClass.getManuApproveScopes());


//                dbClientDetails.setAuthorizedGrantTypes(grantTypes);
//                dbClientDetails.setGrantTypes(organization.getGrantTypes());
//                dbClientDetails.setClientId(organization.getClientId());
//                dbClientDetails.setAllowUsersToJoin(organization.getAllowUsersToJoin());
//                dbClientDetails.setAutoResources(organization.getAutoApproveResources());
//                dbClientDetails.setAutoScopes(organization.getAutoApproveScopes());
//                dbClientDetails.setManuResources(organization.getManuApproveResources());
//                dbClientDetails.setManuScopes(organization.getManuApproveScopes());

            //插入客服端授权信息
            dbClientDetailsService.insertClientDetails(dbClientDetails);
            //插入组织信息
            organizationService.insertOrganization(organization);
            //插入组织部门（默认是顶级部门）
            OrganizationDept organizationDept = new OrganizationDept();
            organizationDept.setClientId(organization.getClientId());
            organizationDept.setDeptId(0 + "");//顶级部门
            organizationDept.setDeptParentId(-1 + "");
            organizationDept.setDeptName(organization.getOrgClassName());
            organizationDept.setDeptPlace(organization.getAddressCode());
            organizationDept.setDeptPlaceDetail(organization.getAddressDetail());
            organizationDept.deptResources(organization.getAutoApproveResources());
            organizationDept.setDeptScopes(organization.getAutoApproveScopes());

            organizationService.insertOrganizationDept(organizationDept);


            responseEntity = new HttpResponseEntity<String>(organization.getClientId(), HttpStatus.OK);
        } catch (Exception e) {
            error = new Error().error("create organization error").errorDescription("create organization exception " + e.getMessage());
            responseEntity = new HttpResponseEntity<String>(error, HttpStatus.INTERNAL_SERVER_ERROR);
        }

        return responseEntity;
    }

    public HttpResponseEntity<String> orgPut(
            @ApiParam(value = "需要更新的个人信息", required = true) @RequestBody Organization organization) {
        // do some magic!
        int count = 0;
        try {
            count = organizationService.updateOrganization(organization);
        } catch (Exception e) {
            Error error = new Error().error("update organization error").errorDescription("update organization exception " + e.getMessage());
            return new HttpResponseEntity<String>(error, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new HttpResponseEntity<String>(count + "", HttpStatus.OK);
    }

    @Override
    public HttpResponseEntity<AuthUserDto> orgCorpGet() {
        return null;
    }


    @Override
    public HttpResponseEntity<String> orgDelete(@ApiParam(value = "组织id", required = true) @RequestParam(value = "orgId", required = true) String orgId) {
        return null;
    }

    /**
     * 注册组织法人
     *
     * @return
     */
    @Override
    public HttpResponseEntity<RegUser> orgCorpPost(
            @ApiParam(value = "法人注册信息", required = true) @RequestBody(required = false) RegUser regUser
    ) {
        int count=0;
        HttpResponseEntity<RegUser> responseEntity = new HttpResponseEntity<RegUser>(HttpStatus.OK);
        Error error = null;
        RegUser regUser1=null;
        try {
             regUser1=orgManage.registerCorp(regUser,autoRecource,autoScopes);
        } catch (Exception e) {
            error = new Error().error("register corp error").errorDescription(e.getMessage());
            responseEntity = new HttpResponseEntity<RegUser>(error, HttpStatus.BAD_REQUEST);
            return responseEntity;
        }
    return new HttpResponseEntity<RegUser>(regUser1,HttpStatus.OK);
}

    @Override
    public HttpResponseEntity<JSONObject> orgCorpBatchPost(@ApiParam(value = "法人注册信息", required = true)@RequestParam(required = true,value="regUserListStr") String regUserListStr) {
        logger.info("regUserListStr="+regUserListStr);
        List<RegUser> regUserList=new ArrayList<>();
        JSONArray jsonArray= JSONArray.fromObject(regUserListStr);
        /**
         * {
         "addressCode": "520206000000",
         "clientName": "江口县电商办",
         "clientOrgClass": "org_ebb_county",
         "nickName": "小勇",
         "orgName": "小勇电商办",
         "password": "123",
         "phoneNumber": "15628048759",
         "realName": "石勇",
         "userName": "jkxdsb"
         }
         * */
        for(int i=0;i<jsonArray.size();i++){
            JSONObject jsonObject=jsonArray.getJSONObject(i);
            RegUser regUser=new RegUser();
            regUser.setDefaultClientId(jsonObject.optString("defaultClientId"));
            regUser.setClientOrgClass(jsonObject.optString("clientOrgClass"));
            regUser.setClientName(jsonObject.optString("clientName"));
            regUser.setAddressCode(jsonObject.optString("addressCode"));
            regUser.setAddressDetail(jsonObject.optString("addressDetail"));
            regUser.setNickName(jsonObject.optString("nickName"));
            regUser.setOrgName(jsonObject.optString("orgName"));
            regUser.setPhoneNumber(jsonObject.optString("phoneNumber"));
            regUser.setRealName(jsonObject.optString("realName"));
            regUser.setUserName(jsonObject.optString("userName"));
            regUser.setPassword("123456");
            regUserList.add(regUser);
        }
        int count=0;
        JSONObject jsonObject=new JSONObject();
        HttpResponseEntity<JSONObject> responseEntity = new HttpResponseEntity<JSONObject>(jsonObject,HttpStatus.OK);
        Error error = null;
        List<RegUser> regUsers=new ArrayList<>();
        try {
            regUsers=  orgManage.batchRegisterCorp(regUserList,autoRecource,autoScopes);
            jsonObject.put("ret_code",0);
            jsonObject.put("result",regUsers.size());
        } catch (Exception e) {
            error = new Error().error("register corp error").errorDescription(e.getMessage());
            jsonObject.put("ret_code",-1);
            jsonObject.put("err_msg",e.getMessage());
        }
        // {    “ret_code”:0,    “err_msg”:”ok”,    “result”:{“status”:0} }
        return new HttpResponseEntity<JSONObject>(jsonObject,HttpStatus.OK);
    }

    @Override
    public HttpResponseEntity<String> importOrgCorp(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
        Error error = new Error();
        if (file == null) {
            error.error("upload file can't be empty").errorDescription("import error");
            return new HttpResponseEntity(error, HttpStatus.MULTI_STATUS);
        }
        List<RegUser> regUserList=new ArrayList<>();

        List<RegUser> regUsers=new ArrayList<>();
        String result =null;
        try {
            regUserList=  readOrgCorp(file);
            regUsers=  orgManage.batchRegisterCorp(regUserList,autoRecource,autoScopes);
        }catch (Exception e){
            error.error("internal server error").errorDescription("import error"+e.getMessage());
            return new HttpResponseEntity(error, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new HttpResponseEntity<String>(regUsers.size()+"",HttpStatus.OK);
    }


    @Override
    public HttpResponseEntity<OrgTotalDTO> orgEmpGet( @ApiParam(value = "组织类型", required = true) @RequestParam(value = "orgClass", required = true) String orgClass,
                                                      @ApiParam(value = "地址代码", required = true) @RequestParam(value = "addressCode", required = true) String addressCode,
                                                      @ApiParam(value = "地址代码", required = false) @RequestParam(value = "group", required = false) String group) {
       //org_class:org_collective
        OrgTotalDTO orgTotalDTO= null;
        try {
            GeoCodings geoCodings=geoCodingsService.getGeoCodingsById(addressCode);
            String geoCode=  SubStringUtil.separateGeoCodeByProduct(geoCodings.getId(),(geoCodings.getRegionLever()+1)+"");
            orgTotalDTO = new OrgTotalDTO();
            int orgTtotal=   organizationService.getOrganizationTotalByClientClass(orgClass,geoCode,addressCode);
            orgTotalDTO.setOrgTotal(orgTtotal+"");
            int fireEmpTotal=organizationService.getOrganizationEmpTotalByOrgClass(orgClass,geoCode,group);
            logger.info("geoCode=="+geoCode);
            int poorTotal=userAuthorityService.getAllPoorCount(geoCode,group);
            logger.info("poorTotal=="+poorTotal);
            DecimalFormat df   = new DecimalFormat("######0.00");
            double fireRate=0;
            String fireRateStr="";
            if(poorTotal>0){
                 fireRate=fireEmpTotal*1.0/poorTotal*100;
                 fireRateStr=  df.format(fireRate);
            }

            logger.info("fireRate=="+fireRate);
            orgTotalDTO.setOrgEmpHireRate(StringUtils.isEmpty(fireRateStr)?(0+"%"):fireRateStr+"%");
        } catch (Exception e) {
          Error error=new Error();
            error.error("invalid_param").errorDescription("query emp total error "+e.getMessage());
            return new HttpResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);
        }

        return new HttpResponseEntity<OrgTotalDTO>(orgTotalDTO, HttpStatus.OK);
    }

    @Override
    public HttpResponseEntity<String> orgClassPost(@ApiParam(value = "组织类型（组织形式）", required = true) @RequestBody OrganizationClass organizationClass) {
      int count=0;
        try {
            count= organizationService.insrertOrganizationClass(organizationClass);
        } catch (Exception e) {
            Error error=new Error();
            error.error("insert organizationClass error").errorDescription("insert organizationClass error "+e.getMessage());
            return new HttpResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new HttpResponseEntity<>(count+"", HttpStatus.OK);
    }

    @Override
    public HttpResponseEntity<List<OrganizationClass>> orgClassGET(@ApiParam(value = "查询组织形式（组织形式）", required = true) @RequestParam(value = "orgClassType(1：农场组织，2：政府组织，3：vimi运营组织)", required = true) Integer orgClassType) {
        List<OrganizationClass> organizationClasses=new ArrayList<>();
        try {
            organizationClasses=organizationService.getOrganizationClassByOrgClassType(orgClassType);
        } catch (Exception e) {
            Error error=new Error();
            error.error("query organizationClass error").errorDescription("query organizationClass error "+e.getMessage());
            return new HttpResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);
        }

        return new HttpResponseEntity< List<OrganizationClass>>(organizationClasses, HttpStatus.OK);
    }

    @Override
    public HttpResponseEntity<List<OrganizationClass>> orgClassPUT(@ApiParam(value = "组织形式", required = true) @RequestParam(value = "组织形式", required = true) @RequestBody OrganizationClass organizationClass) {
        return null;
    }

    @Override
    public HttpResponseEntity<String> orgClassDELETE(@ApiParam(value = "删除组织形式）", required = true) @RequestParam(value = "组织形式id", required = true) String id) {
        return null;
    }

    @Override
    public HttpResponseEntity<Token> changeOrgPost(@ApiParam(value = "组织id", required = true) @RequestParam(value = "orgId", required = true) String orgId, HttpServletRequest request) {
        HttpResponseEntity<String> response=null;
        HttpHeaders responseHttpHeaders=new HttpHeaders();
        responseHttpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
        Error error=new Error().error("invalid_param").errorDescription("param is empty");
         String openId=OAuth2AuthenticationImpl.openId();
         String clientId=OAuth2AuthenticationImpl.clientId();
        if(StringUtils.isEmpty(openId)){
            return new HttpResponseEntity("游客不能切换组织，需要先成为组织里面的员工!", responseHttpHeaders, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        String userId=userAuthorityService.getUserIdByOpenId(openId);
        AuthUserDto authUserDto=  userAuthorityService.getAuthUserDtoByUserId(userId);

        ClientDetails clientDetails =  null;
        try {
            clientDetails =  orgManage.switchOrg(orgId,clientId,openId);
        } catch (Exception ex) {
            error.error("invalid_param").errorDescription(ex.getLocalizedMessage());
            return new HttpResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        LoginUser loginUser=new LoginUser();
       // AuthUserDto authUserDto=userAuthorityService.getLoginUserByClientIdAndOpenId(orgId,openId);

        logger.info("authUserDto="+authUserDto);
        String loginName=StringUtils.isEmpty(authUserDto.getUserName())?(authUserDto.getPhoneNumber()):authUserDto.getUserName();
        //检查clienid是否有效
        if (clientDetails != null) {
            RestTemplate restTemplate = new RestTemplate();
            restTemplate.setErrorHandler(new OAuth2ErrorHandler(new BaseOAuth2ProtectedResourceDetails()));
            HttpHeaders restHeader = new HttpHeaders();
            restHeader.setContentType(MediaType.APPLICATION_JSON_UTF8);
            restHeader.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE);
            restHeader.add("Authorization", "Basic " + CommonUtil.getBASE64(clientDetails.getClientId() + ":" + clientDetails.getClientSecret()));
            String tokenUrl = String.format("/token?grant_type=password&username=%s&password=%s", loginName, authUserDto.getPassword());
            tokenUrl = request.getScheme() + "://" + host + ":" + port + contextPath + tokenUrl;
            HttpEntity<Void> formEntity = new HttpEntity<Void>(restHeader);
            Token token = restTemplate.postForObject(tokenUrl, formEntity, Token.class);
            token.setClientId(clientDetails.getClientId());
            responseHttpHeaders.add("SET-COOKIE", "Authorization=bearer%20" + token.getAccess_token() + ";expire=" + new Date((new Date().getTime()) + token.getExpires_in() * 1000) + ";path=/;HttpOnly");

            return new HttpResponseEntity<Token>(token, responseHttpHeaders, HttpStatus.OK);
        }
        return null;
    }

    @Override
    public HttpResponseEntity<String> approval(@ApiParam(value = "组织id", required = true) @RequestParam(value = "orgId", required = true) String orgId,
                                               @ApiParam(value = "userId", required = false) @RequestParam(value = "userId", required = false) String userId,
                                               @ApiParam(value = "审批是否通过", required = true) @RequestParam(value="isApproval",required = true) int isApproval) {
        Integer count=0;
        try {
            count=orgManage.approval(orgId,userId,isApproval);
        } catch (Exception e) {
            Error error=new Error().error("approval grant error ").errorDescription("approval grant error "+e.getMessage());
            return new HttpResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new HttpResponseEntity<String>(count+"", HttpStatus.OK);
    }

    @Override
    public HttpResponseEntity<String> applyAddOrg(
            @ApiParam(value = "组织id", required = true) @RequestParam(value = "orgId", required = true) String orgId,
            @ApiParam(value = "工种（org_manager:管理员,  org_shareholder：只是股东，不是员工， org_shareholder_emp：既是股东又是员工，org_senior_manager:高级管理员，org_shareholder_manager： 既是管理员又是股东，org_shareholder_senior_manager：既是股东又是高级管理员, org_emp:组织里面的员工）", required = true) @RequestParam(value = "job", required = true) String job
    ) {
        int count=0;
        String openId=OAuth2AuthenticationImpl.openId();
        try {
            count=orgManage.applyAddOrg(orgId,openId,job);
        } catch (Exception e) {
            return new HttpResponseEntity<String>("-1", HttpStatus.OK);
        }
        return new HttpResponseEntity<String>(count+"", HttpStatus.OK);
    }

    @Override
    public HttpResponseEntity<OrgMemberTotalDTO> orgMemberTotal(@ApiParam(value = "组织id(不传的时候以当前登录的组织id为准)", required = false) @RequestParam(value = "orgId", required = false) String orgId) {

        OrgMemberTotalDTO orgMemberTotalDTO=new OrgMemberTotalDTO();
         int empTotal=0;//员工数
         int shareholderTotal=0;//股东数
         int poorPersonsTotal=0;//贫困人口数
         int poorHouseholdTotal=0;//贫困户总数
        int fans=0;//粉丝
        String clientId=OAuth2AuthenticationImpl.clientId();
        if(!StringUtils.isEmpty(orgId)){
            clientId=orgId;
        }
        try {
            orgMemberTotalDTO=  userAuthorityService.getOrgMemberTotal(clientId);
            empTotal=organizationService.getOrgEmpTotal(clientId);
            orgMemberTotalDTO.setEmpTotal(empTotal);
            shareholderTotal=organizationService.getOrgShareHolderTotal(clientId);
            orgMemberTotalDTO.setShareholderTotal(shareholderTotal);
            fans=  relationService.getFarmFansCount(clientId);
            orgMemberTotalDTO.setFans(fans);
        } catch (Exception e) {
            Error error=new Error().error("get total error").errorDescription("get total error "+e.getMessage());
            return new HttpResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new HttpResponseEntity<OrgMemberTotalDTO>(orgMemberTotalDTO, HttpStatus.OK);
    }

    private String getAllAddress(String addressCode) {
        String farmAdress="";
        Map<String,String> geoCodingsMap= CommonUtil.parseGeoCodings(addressCode);
        String  city=geoCodingsService.getGeoCodingsById(geoCodingsMap.get("city")).getGeoName();
        String  county=geoCodingsService.getGeoCodingsById(geoCodingsMap.get("county")).getGeoName();
        String  vilage=geoCodingsService.getGeoCodingsById(geoCodingsMap.get("vilage")).getGeoName();
        String  burg=geoCodingsService.getGeoCodingsById(geoCodingsMap.get("burg")).getGeoName();
        if(!StringUtils.isEmpty(city)){
            farmAdress+=city;
        }
        if(!StringUtils.isEmpty(county)){
            farmAdress+=county;
        }
        if(!StringUtils.isEmpty(vilage)){
            farmAdress+=vilage;
        }
        if(!StringUtils.isEmpty(burg)){
            farmAdress+=burg;
        }
        return farmAdress;
    }



    public static boolean isMobileNO(String mobiles) {
        Pattern p = Pattern.compile("^((13[0-9])|(15[0-9])|(17[0-9])|(18[0-9]))\\d{8}$");
        Matcher m = p.matcher(mobiles);
        System.out.println(m.matches() + "---");
        return m.matches();
    }
    private List<RegUser> readOrgCorp(MultipartFile multipartFile){
        List<RegUser> regUserList=new ArrayList<>();
        try {
            //打开文件
            Workbook book = Workbook.getWorkbook(multipartFile.getInputStream());
            //取得第一个sheet
            Sheet sheet = book.getSheet(0);
            //取得行数
            int rows = sheet.getRows();
            for (int i = 2; i < rows; i++) {
                Cell[] cell = sheet.getRow(i);
                for (int j = 0; j < cell.length; j++) {
                    System.out.println(cell[j].getContents());
                }
                RegUser regUser = new RegUser();

                //组织类型
                String orgClass = sheet.getCell(0, i).getContents();
                if (!StringUtils.isEmpty(orgClass)) {
                    regUser.setClientOrgClass(orgClass);
                }

                //组织名字
                String orgName = sheet.getCell(1, i).getContents();
                if (!StringUtils.isEmpty(orgName)) {
                    regUser.setOrgName(orgName);
                }

                //组织用户名
                String userName = sheet.getCell(2,i).getContents();
                    if(!StringUtils.isEmpty(userName)){
                            regUser.setUserName(userName);

                    }



                //地址码
                String addressCode = sheet.getCell(3, i).getContents();
                if (!StringUtils.isEmpty(addressCode)) {
                    regUser.setAddressCode(addressCode);
                }

                //地址详情
                String addressDetail = sheet.getCell(4, i).getContents();
                if (!StringUtils.isEmpty(addressDetail)) {
                    regUser.setAddressDetail(addressDetail);
                }


                if(!StringUtils.isEmpty(regUser.getUserName())){
                    regUser.setPassword("123456");
                    regUserList.add(regUser);
                }

            }
            //关闭文件
            book.close();
        } catch (Exception e) {
            logger.error("数据读取出错！", e);
        }
        return  regUserList;
    }

}
